<template>
  <div>
    <h3>贷款计算器</h3>

    <h4>
      <van-tag type="primary" size="large">{{
        this.bankInfo.bankName
      }}</van-tag>
    </h4>

    <van-tag color="#ffe1e1" text-color="#ad0000">政策导读</van-tag>

    <van-tag color="#ffffff" text-color="#7f7f7f">{{
      this.getPolicies
    }}</van-tag>

    <van-form @submit="onSubmit" scroll-to-error ref="form">
      <van-field
        name="loanPrice"
        v-model="price"
        label="贷款金额"
        placeholder="单位:万元"
      >
        <template #extra>
          万元
        </template>
      </van-field>
      <van-field
        name="loanTerm"
        v-model="term"
        label="期限"
        placeholder="单位:月"
      >
        <template #extra>
          月
        </template>
      </van-field>
      <van-field
        name="loanRate"
        v-model="rate"
        label="贷款年利率"
        placeholder="请输入百分数,如: 4.65"
      >
        <template #extra>
          %
        </template>
      </van-field>
      <van-field name="loanType" label="单选框">
        <template #input>
          <van-radio-group v-model="loanType" direction="horizontal">
            <van-radio name="1">等额本金</van-radio>
            <van-radio name="2">等额本息</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-button round type="primary" native-type="submit" class="submit-btn">
        开始计算
      </van-button>
      <CalculatorTable
        v-if="this.step === 5"
        :tableData="tableData"
        :totalData="totalData"
      ></CalculatorTable>
    </van-form>
  </div>
</template>

<script>
import Toast from "vant";
import CalculatorTable from "./CalculatorTable";

export default {
  name: "CalculatorForm",
  components: {
    CalculatorTable
  },
  props: {
    bankInfo: Object
  },
  inject: ["changeStep"],
  data() {
    return {
      step: 4,
      loanType: "1",
      price: "",
      term: "",
      rate: "",
      totalData: {},
      tableData: []
    };
  },
  computed: {
    getPolicies() {
      let policies = this.bankInfo.policies;
      if (policies.length < 2 && policies.indexOf("0") != -1) {
        return "暂无";
      } else {
        return policies.join();
      }
    }
  },
  methods: {
    onSubmit(values) {
      let formData = values;
      this.calculator(formData);
      this.step = 5;
    },
    onChange(picker, value, index) {
      Toast(`当前值：${value}, 当前索引：${index}`);
    },
    calculator(formData) {
      let loanType = formData.loanType;
      if (loanType == 1) {
        this.equalPrincipal(formData);
      } else if (loanType == 2) {
        this.equalPrincipalAndInterest(formData);
      } else {
        console.log("参数错误");
      }

      this.getTotalData(loanType);
    },
    equalPrincipalAndInterest(formData) {
      // 计算等额本息
      let loanPrice = formData.loanPrice * 10000;
      let loanTerms = formData.loanTerm;
      let loanRate = formData.loanRate / 100;
      let calcTableData = new Array();
      let monLoanRate = loanRate / 12; // 月利率
      let firstMonInterest = loanPrice * monLoanRate; // 第一个月的利息 = 贷款总额 * 月利率
      let sumPrincipal = 0; // 已缴纳的本金
      for (let i = 0; i < loanTerms; i++) {
        // i 是贷款当前月，从 0 ～ (length - 1)
        let monPayment =
          (loanPrice * monLoanRate * Math.pow(1 + monLoanRate, loanTerms)) /
          (Math.pow(1 + monLoanRate, loanTerms) - 1); // 借款本金×月利率×（1＋月利率）^还款月数/[（1＋月利率）^还款月数－1]
        let monInterest;
        if (i == 0) {
          monInterest = firstMonInterest; // 第一个月的利息
        } else {
          monInterest = (loanPrice - sumPrincipal) * monLoanRate; // 每个月的利息 = 剩余本金 * 月利率
        }
        let monPrincipal = monPayment - monInterest; // 每个月的本金 = 月供 - 月利息
        sumPrincipal += monPrincipal; // 计算已缴纳的本金
        let balance = loanPrice - sumPrincipal;
        if (loanTerms == i + 1) {
          balance = 0.0; // 最后一个月，余额要置0
        }
        let rowData = {
          term: i + 1,
          monPayment: this.myRound(monPayment), // 月供
          monPrincipal: this.myRound(monPrincipal), // 月供本金
          monInterest: this.myRound(monInterest), // 月供利息
          balance: this.myRound(balance) // 剩余本金
        };
        calcTableData.push(rowData);
      }
      this.tableData = calcTableData;
    },
    equalPrincipal(formData) {
      // 计算等额本金
      let loanPrice = formData.loanPrice * 10000;
      let loanTerms = formData.loanTerm;
      let loanRate = formData.loanRate / 100;
      let calcTableData = new Array();
      for (let i = 0; i < loanTerms; i++) {
        // i 是贷款当前月，从 0 ～ (length - 1)
        let monPrincipal = loanPrice / loanTerms; // 每月还款本金=贷款总额/贷款月数 ；
        let balance = loanPrice - (i + 1) * monPrincipal; // 贷款本金余额=贷款总额-已还款月数*每月还款本金
        if (loanTerms == i + 1) {
          balance = 0.0; // 最后一个月，余额要置0
        }
        let monInterest = (loanPrice - i * monPrincipal) * (loanRate / 12); // 每月还款利息=贷款本金余额*贷款月利率（贷款月利率=年利率/12）
        let monPayment = monPrincipal + monInterest; // 每月还款额=每月还款本金+每月还款利息；

        let rowData = {
          term: i + 1,
          monPayment: this.myRound(monPayment),
          monPrincipal: this.myRound(monPrincipal),
          monInterest: this.myRound(monInterest),
          balance: this.myRound(balance)
        };
        calcTableData.push(rowData);
      }
      this.tableData = calcTableData;
    },

    getTotalData(loanType) {
      // 获取合计数据（月供总和、利息总和）
      let tableData = this.tableData;
      let sumPayment = tableData.reduce(function(total, currentValue) {
        return total + currentValue.monPayment;
      }, 0);
      let sumInterest = tableData.reduce(function(total, currentValue) {
        return total + currentValue.monInterest;
      }, 0);

      this.totalData = {
        loanType: loanType,
        sumPayment: this.myRound(sumPayment),
        sumInterest: this.myRound(sumInterest)
      };
    },

    myRound(aNum) {
      return Math.round(aNum * 100) / 100;
    }
  }
};
</script>

<style>
.return-btn {
  position: absolute;
  top: 16px;
  right: 24px;
}
</style>
